{% extends "base.html" %}

{% block title %}{{ '编辑任务' if task else '创建任务' }} - XbyJob{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">{{ '编辑任务' if task else '创建任务' }}</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <a href="{{ url_for('dashboard.tasks') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i>返回列表
            </a>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-body">
                <form id="taskForm">
                    <input type="hidden" id="taskId" value="{{ task.id if task else '' }}">
<input type="hidden" id="userScriptId" value="{{ task.user_script_id if task and task.user_script_id else '' }}">
<input type="hidden" id="notificationConfigId" value="{{ task.notification_config_id if task and task.notification_config_id else '' }}">
                    
                    <!-- 基本信息 -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="taskName" class="form-label">任务名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="taskName" required
                                       value="{{ task.name if task else '' }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <!-- 任务类型固定为Python脚本，不需要选择 -->
                            <input type="hidden" id="taskType" value="python_script">
                            
                            <div class="mb-3">
                                <label for="userScriptSelect" class="form-label">选择脚本 <span class="text-danger">*</span></label>
                                <select class="form-select" id="userScriptSelect" required>
                                    <option value="">请选择一个脚本...</option>
                                </select>
                                <div class="form-text">选择你创建的Python脚本</div>
                                
                                <!-- 脚本预览按钮 -->
                                <div id="scriptPreviewButtonArea" class="mt-2" style="display: none;">
                                    <button type="button" class="btn btn-outline-info btn-sm" onclick="showScriptPreview()">
                                        <i class="fas fa-eye me-1"></i>预览脚本内容
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="taskDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="taskDescription" rows="2">{{ task.description if task else '' }}</textarea>
                    </div>
                    
                    <!-- 调度配置 -->
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label for="cronExpression" class="form-label">Cron表达式 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="cronExpression" required 
                                       placeholder="例如: 0 0 * * *" value="{{ task.cron_expression if task else '' }}">
                                <div class="form-text">
                                    <span id="cronDescription"></span>
                                    <a href="#" onclick="showCronHelp()">查看帮助</a>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">预览下次执行</label>
                                <div class="border rounded p-2 bg-light">
                                    <small id="nextRunPreview" class="text-muted">请输入Cron表达式</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 执行内容部分已移除，现在使用用户脚本 -->
                    
                    <!-- 执行配置 -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="timeout" class="form-label">超时时间(秒)</label>
                                <input type="number" class="form-control" id="timeout" value="{{ task.timeout if task else 0 }}" min="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="retryAttempts" class="form-label">重试次数</label>
                                <input type="number" class="form-control" id="retryAttempts" value="{{ task.retry_attempts if task else 0 }}" min="0" max="5">
                                <div class="form-text">设置为0表示不重试，1-5表示失败后重试的次数</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 环境变量 -->
                    <div class="mb-3">
                        <label class="form-label">环境变量</label>
                        <div id="envVarsContainer">
                            {% if task and task.environment_variables is not none %}
                                {% for key, value in task.environment_variables.items() %}
                                <div class="row mb-2 env-var-row">
                                    <div class="col-5">
                                        <input type="text" class="form-control env-var-key" placeholder="变量名" value="{{ key }}">
                                    </div>
                                    <div class="col-5">
                                        <input type="text" class="form-control env-var-value" placeholder="变量值" value="{{ value }}">
                                    </div>
                                    <div class="col-2">
                                        <button type="button" class="btn btn-outline-danger" onclick="removeEnvVar(this)">
                                            <i class="fas fa-minus"></i>
                                        </button>
                                    </div>
                                </div>
                                {% endfor %}
                            {% endif %}
                            <div class="row mb-2 env-var-row">
                                <div class="col-5">
                                    <input type="text" class="form-control env-var-key" placeholder="变量名">
                                </div>
                                <div class="col-5">
                                    <input type="text" class="form-control env-var-value" placeholder="变量值">
                                </div>
                                <div class="col-2">
                                    <button type="button" class="btn btn-outline-success" onclick="addEnvVar()">
                                        <i class="fas fa-plus"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="form-text">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="showEnvVarHelp()">
                                <i class="fas fa-question-circle me-1"></i>查看帮助
                            </button>
                        </div>
                    </div>
                    
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="isEnabled" {{ 'checked' if not task or task.is_enabled else '' }}>
                        <label class="form-check-label" for="isEnabled">
                            启用任务
                        </label>
                    </div>
                    
                    <!-- 通知配置 -->
                    <div class="mb-3">
                        <h6><i class="fas fa-bell me-2"></i>失败通知设置</h6>
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="checkbox" id="notifyOnFailure" {{ 'checked' if task and task.notify_on_failure else '' }}>
                            <label class="form-check-label" for="notifyOnFailure">
                                任务执行失败时发送通知
                            </label>
                        </div>
                        
                        <div id="notificationConfigSection" style="display: {{ 'block' if task and task.notify_on_failure else 'none' }};">
                            <div class="mb-2">
                                <label for="notificationConfig" class="form-label">选择通知配置</label>
                                <select class="form-select" id="notificationConfig">
                                    <option value="">请选择通知配置</option>
                                    <!-- 通知配置选项将通过JavaScript动态加载 -->
                                </select>
                                <div class="form-text">
                                    <a href="/notification-config" target="_blank" class="text-decoration-none">
                                        <i class="fas fa-cog me-1"></i>管理通知配置
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <div>
                            <button type="button" class="btn btn-primary" onclick="saveTask()">
                                <i class="fas fa-save me-1"></i>保存
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="resetForm()">
                                <i class="fas fa-undo me-1"></i>重置
                            </button>
                        </div>

                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <!-- 任务类型说明 -->
        <div class="card mb-4">
            <div class="card-header">
                <h6><i class="fas fa-info-circle me-2"></i>Python脚本任务</h6>
            </div>
            <div class="card-body">
                <div id="taskTypeHelp">
                    <h6>Python脚本执行</h6>
                    <p>执行你上传的Python脚本文件。系统会自动安装脚本所需的依赖包，并在指定的工作目录中运行脚本。</p>
                    <h6>使用说明:</h6>
                    <ul>
                        <li>选择已上传的Python脚本文件</li>
                        <li>可以设置环境变量供脚本使用</li>
                        <li>支持自动安装依赖包</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- Cron表达式示例 -->
        <div class="card">
            <div class="card-header">
                <h6><i class="fas fa-clock me-2"></i>Cron表达式示例</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <tbody>
                            <tr>
                                <td><code>0 0 * * *</code></td>
                                <td>每天午夜</td>
                            </tr>
                            <tr>
                                <td><code>*/5 * * * *</code></td>
                                <td>每5分钟</td>
                            </tr>
                            <tr>
                                <td><code>0 9 * * 1-5</code></td>
                                <td>工作日9点</td>
                            </tr>
                            <tr>
                                <td><code>0 0 1 * *</code></td>
                                <td>每月1号</td>
                            </tr>
                            <tr>
                                <td><code>0 */2 * * *</code></td>
                                <td>每2小时</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <button type="button" class="btn btn-outline-primary btn-sm w-100" onclick="showCronHelp()">
                    查看详细帮助
                </button>
            </div>
        </div>
        
        <!-- 环境变量说明 -->
        <div class="card mt-4">
            <div class="card-header">
                <h6><i class="fas fa-cog me-2"></i>环境变量说明</h6>
            </div>
            <div class="card-body">
                <p>环境变量可以在任务执行时提供配置信息：</p>
                <ul>
                    <li><strong>Python脚本</strong>: 通过 <code>os.environ['VAR_NAME']</code> 访问</li>

                </ul>
                <button type="button" class="btn btn-outline-primary btn-sm w-100" onclick="showEnvVarHelp()">
                    查看详细帮助
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 脚本预览模态框 -->
<div class="modal fade" id="scriptPreviewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">脚本内容预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">脚本名称：</label>
                    <span id="previewScriptName" class="fw-bold"></span>
                </div>
                <div class="mb-3">
                    <label class="form-label">脚本路径：</label>
                    <span id="previewScriptPath" class="text-muted"></span>
                </div>
                <div class="mb-3">
                    <label class="form-label">脚本内容：</label>
                    <pre id="previewScriptContent" class="bg-light p-3 rounded" style="max-height: 400px; overflow-y: auto; font-size: 0.9em;"></pre>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- Cron帮助模态框 -->
<div class="modal fade" id="cronHelpModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Cron表达式帮助</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <h6>格式说明</h6>
                <p>Cron表达式由5个字段组成，用空格分隔：</p>
                <code>分钟 小时 日 月 星期</code>
                
                <h6 class="mt-3">字段范围</h6>
                <ul>
                    <li>分钟: 0-59</li>
                    <li>小时: 0-23</li>
                    <li>日: 1-31</li>
                    <li>月: 1-12</li>
                    <li>星期: 0-7 (0和7都表示周日)</li>
                </ul>
                
                <h6 class="mt-3">特殊字符</h6>
                <ul>
                    <li><code>*</code> 表示任意值</li>
                    <li><code>,</code> 表示列表，如 1,3,5</li>
                    <li><code>-</code> 表示范围，如 1-5</li>
                    <li><code>/</code> 表示步长，如 */5 表示每5个单位</li>
                </ul>
                
                <h6 class="mt-3">更多示例</h6>
                <table class="table table-sm">
                    <tr><td><code>30 2 * * *</code></td><td>每天凌晨2:30</td></tr>
                    <tr><td><code>0 0 * * 0</code></td><td>每周日午夜</td></tr>
                    <tr><td><code>15 10 * * 1-5</code></td><td>工作日上午10:15</td></tr>
                    <tr><td><code>0 0 1,15 * *</code></td><td>每月1号和15号</td></tr>
                    <tr><td><code>*/15 9-17 * * 1-5</code></td><td>工作日工作时间每15分钟</td></tr>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 环境变量帮助模态框 -->
<div class="modal fade" id="envVarHelpModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">环境变量使用帮助</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <h6>什么是环境变量？</h6>
                <p>环境变量是在任务执行时提供给脚本或命令的运行时配置参数。</p>
                
                <h6 class="mt-3">使用场景</h6>
                <ul>
                    <li><strong>配置脚本行为</strong>: 控制日志级别、指定配置文件路径等</li>
                    <li><strong>敏感信息管理</strong>: 传递API密钥、数据库密码等敏感信息</li>
                    <li><strong>环境区分</strong>: 区分开发、测试、生产环境</li>
                    <li><strong>资源定位</strong>: 指定数据文件路径、临时目录等</li>
                </ul>
                
                <h6 class="mt-3">访问方式</h6>
                <div class="card mb-3">
                    <div class="card-header">
                        <strong>Python脚本</strong>
                    </div>
                    <div class="card-body">
                        <pre class="bg-light p-2 rounded"><code>import os

# 获取环境变量
api_key = os.environ.get('API_KEY')
database_url = os.environ.get('DATABASE_URL')

# 设置默认值
log_level = os.environ.get('LOG_LEVEL', 'INFO')

# 使用环境变量
print(f"API Key: {api_key}")
print(f"Database URL: {database_url}")
print(f"Log Level: {log_level}")</code></pre>
                    </div>
                </div>
                

                
                <h6 class="mt-3">公共参数</h6>
                <div class="alert alert-info">
                    <p class="mb-2"><strong>除了任务环境变量，您还可以使用公共参数：</strong></p>
                    <ul class="mb-2">
                        <li>在 <strong>用户名 → 公共参数</strong> 中设置全局参数</li>
                        <li>公共参数会自动注入到所有任务的执行环境中</li>
                        <li>参数名会自动添加 <code>GLOBAL_</code> 前缀，例如：<code>GLOBAL_API_KEY</code></li>
                        <li>适用于跨任务共享的配置信息，如API密钥、数据库连接等</li>
                    </ul>
                    <p class="mb-0">
                        <a href="{{ url_for('dashboard.global_parameters') }}" target="_blank" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-cogs me-1"></i>管理公共参数
                        </a>
                    </p>
                </div>
                
                <h6 class="mt-3">示例</h6>
                <p>添加以下环境变量：</p>
                <ul>
                    <li><strong>API_KEY</strong>: abc123def456</li>
                    <li><strong>DATABASE_URL</strong>: postgresql://user:pass@localhost/db</li>
                    <li><strong>LOG_LEVEL</strong>: DEBUG</li>
                </ul>
                <p class="text-muted">注意：如果设置了公共参数 <code>api_key</code>，脚本中可以通过 <code>os.environ.get('GLOBAL_API_KEY')</code> 访问。</p>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
const taskTypeHelp = {
    'python_script': {
        title: 'Python脚本',
        content: '直接执行Python代码。支持多行脚本，可以使用标准库和已安装的第三方包。',
        example: 'import requests\nprint("Hello, XbyJob!")\nresponse = requests.get("https://httpbin.org/json")\nprint(response.json())'
    },

};

$(document).ready(function() {
    // 任务类型变化事件
    $('#taskType').change(function() {
        const taskType = $(this).val();
        updateTaskTypeHelp(taskType);
        updateCommandHelp(taskType);
    });
    
    // Cron表达式验证
    $('#cronExpression').on('input', function() {
        const expression = $(this).val();
        if (expression) {
            validateCronExpression(expression);
        } else {
            $('#cronDescription').text('');
            $('#nextRunPreview').text('请输入Cron表达式');
        }
    });
    
    // 初始化 - 任务类型固定为Python脚本
    
    // 加载用户脚本列表
    loadUserScripts();
    
    // 脚本选择变化事件
    $('#userScriptSelect').change(function() {
        const scriptId = $(this).val();
        if (scriptId) {
            $('#scriptPreviewButtonArea').show();
        } else {
            $('#scriptPreviewButtonArea').hide();
        }
    });
    
    // 通知开关变化事件
    $('#notifyOnFailure').change(function() {
        const isChecked = $(this).is(':checked');
        $('#notificationConfigSection').toggle(isChecked);
        if (isChecked && $('#notificationConfig option').length <= 1) {
            loadNotificationConfigs();
        }
    });
    
    // 加载通知配置列表
    loadNotificationConfigs();
    
    const currentCron = $('#cronExpression').val();
    if (currentCron) {
        validateCronExpression(currentCron);
    }
});

function updateTaskTypeHelp(taskType) {
    const helpDiv = $('#taskTypeHelp');
    
    if (taskType && taskTypeHelp[taskType]) {
        const help = taskTypeHelp[taskType];
        helpDiv.html(`
            <h6>${help.title}</h6>
            <p>${help.content}</p>
            <h6>示例:</h6>
            <pre class="bg-light p-2 rounded"><code>${help.example}</code></pre>
        `);
    } else {
        helpDiv.html('<p class="text-muted">请选择任务类型查看说明</p>');
    }
}

function updateCommandHelp(taskType) {
    const helpTexts = {
        'python_script': '请输入Python代码，支持多行脚本',

    };
    
    $('#commandHelp').text(helpTexts[taskType] || '请输入要执行的内容');
}


function validateCronExpression(expression) {
    $.ajax({
        url: '/api/cron/validate',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({expression: expression})
    })
    .done(function(response) {
        if (response.success) {
            $('#cronExpression').removeClass('is-invalid').addClass('is-valid');
            $('#cronDescription').text('有效的Cron表达式').removeClass('text-danger').addClass('text-success');
            
            // 获取下次执行时间预览
            getNextRunPreview(expression);
        } else {
            $('#cronExpression').removeClass('is-valid').addClass('is-invalid');
            $('#cronDescription').text('无效的Cron表达式').removeClass('text-success').addClass('text-danger');
            $('#nextRunPreview').text('表达式无效');
        }
    })
    .fail(function() {
        $('#cronExpression').removeClass('is-valid').addClass('is-invalid');
        $('#cronDescription').text('验证失败').removeClass('text-success').addClass('text-danger');
    });
}

function getNextRunPreview(expression) {
    $.ajax({
        url: '/api/cron/parse',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({expression: expression})
    })
    .done(function(response) {
        if (response.success && response.data.next_run_times) {
            const nextRuns = response.data.next_run_times.slice(0, 3);
            const preview = nextRuns.map(time => new Date(time).toLocaleString()).join('<br>');
            $('#nextRunPreview').html(`接下来3次执行:<br>${preview}`);
        }
    });
}

function addEnvVar() {
    const container = $('#envVarsContainer');
    const newRow = `
        <div class="row mb-2 env-var-row">
            <div class="col-5">
                <input type="text" class="form-control env-var-key" placeholder="变量名">
            </div>
            <div class="col-5">
                <input type="text" class="form-control env-var-value" placeholder="变量值">
            </div>
            <div class="col-2">
                <button type="button" class="btn btn-outline-danger" onclick="removeEnvVar(this)">
                    <i class="fas fa-minus"></i>
                </button>
            </div>
        </div>
    `;
    
    // 在最后一行之前插入
    container.children().last().before(newRow);
}

function removeEnvVar(button) {
    $(button).closest('.env-var-row').remove();
}


function collectEnvVars() {
    const envVars = {};
    $('#envVarsContainer .env-var-row').each(function() {
        const key = $(this).find('.env-var-key').val().trim();
        const value = $(this).find('.env-var-value').val().trim();
        if (key && value) {
            envVars[key] = value;
        }
    });
    return envVars;
}


function saveTask() {
    // 收集表单数据
    const selectedScriptId = $('#userScriptSelect').val();
    const taskData = {
        name: $('#taskName').val().trim(),
        description: $('#taskDescription').val().trim(),
        task_type: $('#taskType').val(),
        cron_expression: $('#cronExpression').val().trim(),
        user_script_id: selectedScriptId ? parseInt(selectedScriptId) : null,
        timeout: parseInt($('#timeout').val()),
        retry_attempts: parseInt($('#retryAttempts').val()),
        is_enabled: $('#isEnabled').is(':checked'),
        notify_on_failure: $('#notifyOnFailure').is(':checked'),
        notification_config_id: $('#notificationConfig').val() ? parseInt($('#notificationConfig').val()) : null,
        environment_variables: collectEnvVars()
    };
    
    // 验证必需字段
    if (!taskData.name || !taskData.task_type || !taskData.cron_expression || !taskData.user_script_id) {
        showAlert('请填写所有必需字段并选择脚本', 'warning');
        return;
    }
    
    const taskId = $('#taskId').val();
    const isEdit = taskId && taskId.trim() !== '';
    const url = isEdit ? `/api/tasks/${taskId}` : '/api/tasks';
    const method = isEdit ? 'PUT' : 'POST';
    
    console.log('TaskId:', taskId, 'IsEdit:', isEdit, 'URL:', url, 'Method:', method);
    
    // 显示保存中状态
    const saveBtn = $('button[onclick="saveTask()"]');
    const originalText = saveBtn.html();
    saveBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>保存中...');
    
    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(taskData)
    })
    .done(function(response) {
        if (response.success) {
            showAlert(isEdit ? '任务更新成功' : '任务创建成功', 'success');
            setTimeout(function() {
                window.location.href = '/dashboard/tasks';
            }, 1500);
        } else {
            showAlert('保存失败: ' + response.message, 'danger');
        }
    })
    .fail(function() {
        showAlert('网络错误，请稍后重试', 'danger');
    })
    .always(function() {
        saveBtn.prop('disabled', false).html(originalText);
    });
}



function resetForm() {
    if (!confirm('确定要重置表单吗？所有未保存的更改将丢失。')) {
        return;
    }
    
    $('#taskForm')[0].reset();
    $('#cronExpression').removeClass('is-valid is-invalid');
    $('#cronDescription').text('');
    $('#nextRunPreview').text('请输入Cron表达式');
    
    // 清空动态添加的环境变量和依赖包
    $('.env-var-row').remove();
    $('.dependency-row').remove();
    
    updateTaskTypeHelp('');
    updateCommandHelp('');
    $('#dependenciesSection').hide();
}

function showCronHelp() {
    $('#cronHelpModal').modal('show');
}

function showEnvVarHelp() {
    $('#envVarHelpModal').modal('show');
}

function loadUserScripts() {
    $.get('/api/scripts?per_page=1000')
        .done(function(response) {
            if (response.success) {
                const select = $('#userScriptSelect');
                select.empty().append('<option value="">请选择一个脚本...</option>');
                
                response.data.scripts.forEach(function(script) {
                    if (script.language === 'python' && script.is_active) {
                        // 使用API返回的完整路径
                        const fullPath = script.full_path + '.py';
                        const option = `<option value="${script.id}">${script.name} (${fullPath})</option>`;
                        select.append(option);
                    }
                });
                
                // 如果是编辑模式，设置选中的脚本
                const taskId = $('#taskId').val();
                if (taskId) {
                    // 从隐藏字段获取任务的user_script_id
                    const userScriptId = $('#userScriptId').val();
                    if (userScriptId) {
                        select.val(userScriptId);
                        // 显示脚本预览按钮
                        $('#scriptPreviewButtonArea').show();
                    }
                }
            }
        })
        .fail(function() {
            console.error('加载用户脚本失败');
        });
}

function loadNotificationConfigs() {
    $.get('/api/notification-configs')
        .done(function(response) {
            if (response.success) {
                const select = $('#notificationConfig');
                select.empty().append('<option value="">请选择通知配置</option>');
                
                response.data.forEach(function(config) {
                    const option = `<option value="${config.id}">${config.name}</option>`;
                    select.append(option);
                });
                
                // 如果是编辑模式，设置选中的通知配置
                const taskId = $('#taskId').val();
                if (taskId) {
                    const notificationConfigId = $('#notificationConfigId').val();
                    if (notificationConfigId) {
                        select.val(notificationConfigId);
                    }
                }
            }
        })
        .fail(function() {
            console.error('加载通知配置失败');
        });
}

function showScriptPreview() {
    const scriptId = $('#userScriptSelect').val();
    if (!scriptId) {
        showAlert('请先选择一个脚本', 'warning');
        return;
    }
    
    previewSelectedScript(scriptId);
}

function previewSelectedScript(scriptId) {
    $.get(`/api/scripts/${scriptId}`)
        .done(function(response) {
            if (response.success) {
                const script = response.data;
                
                // 设置模态框内容
                $('#previewScriptName').text(script.name);
                $('#previewScriptPath').text(script.full_path + '.py');
                $('#previewScriptContent').text(script.content);
                
                // 显示模态框
                $('#scriptPreviewModal').modal('show');
            } else {
                showAlert('获取脚本内容失败: ' + response.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('获取脚本内容失败', 'danger');
        });
}

function showAlert(message, type) {
    // 使用基础模板中定义的全局showMessage函数（即showToast）
    if (typeof window.showMessage === 'function') {
        // 映射类型到Toast支持的类型
        let toastType = type;
        switch(type) {
            case 'danger':
                toastType = 'error';
                break;
            case 'warning':
                toastType = 'warning';
                break;
            case 'success':
                toastType = 'success';
                break;
            default:
                toastType = 'info';
        }
        showMessage(message, toastType, 3000);
    } else {
        // 如果全局函数不可用，回退到原来的实现
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('.container-fluid').prepend(alertHtml);
        
        setTimeout(function() {
            $('.alert').alert('close');
        }, 3000);
    }
}
</script>
{% endblock %}